Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
React "append" component to DOM?

I'm new to React and I'm trying to render a component when a user tries to login with wrong login details. I have a Login.jsx page where I render the login form, and handles all the login logic in a async function. This all works fine. If the login details are wrong I have an ErrorModal component render in at an already set div with the ID of error-modal.

ReactDOM.render(<ErrorModal />, document.getElementById('error-modal'))
...

function Login() {
  const userRef = React.useRef()
  const passRef = React.useRef()
  const loginErr = React.useRef()
  const handleLogin = async (e) => {
    e.preventDefault()
    requestLogin(userRef.current.value, passRef.current.value, loginErr)
  }

  return (
    <form className='login-form' onSubmit={handleLogin}>
        <Field ref={userRef} label='Username:' type='text' />
        <Field ref={passRef} label='Password:' type='password' />
        <div className='button-wrapper'>
          <button type='submit' className='btn'>Login</button>
        </div>
        <div id='error-modal'></div>
    </form>
  )
}

export default Login

Do I need to have the error-modal div already in the DOM, or can I just append the ErrorModal component after another DOM element somehow (like inside the form or just outside the form) and not worry about the error-modal div being "hard coded"?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You should use Conditional Rendering.

Here's an example:

function Login() {
  const [userCredentials, setUserCredentials] = useState({
    email: "",
    password: ""
  });

  const [error, setError] = useState(false);

  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      const res = await requestLogin(userCredentials);
      if (!res.ok) {
        throw Error("Login failed...");
      }
    } catch (e) {
      setError(true);
      console.error(e);
    }
  };

  const handleUserCredentialsChange = (e) => {
    setUserCredentials({ ...userCredentials, [e.target.name]: e.target.value });
  };
    
  return (
    <>
      <form onSubmit={handleLogin}>
        <input
          placeholder="Email"
          name="email"
          value={userCredentials.email}
          onChange={handleUserCredentialsChange}
        />
        <input
          placeholder="Password"
          name="password"
          value={userCredentials.password}
          type="password"
          onChange={handleUserCredentialsChange}
        />
        <input type="submit" />
      </form>
      {error && (
        <div style={modalContainer}>
          <div style={{ backgroundColor: "aliceblue", padding: 40 }}>
            <h1>Something went wrong...</h1>
            <button onClick={() => setError(false)}>Close</button>
          </div>
        </div>
      )}
    </>
  );
}

function requestLogin(userCredentials) {
  return fetch("api/login", {
    method: "POST",
    body: JSON.stringify(userCredentials),
    headers: {
      "Content-Type": "application/json"
    }
  });
}

const modalContainer = {
  position: "absolute",
  zIndex: 100,
  top: 0,
  bottom: 0,
  left: 0,
  right: 0,
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  backgroundColor: "rgba(0,0,0,0.5)"
};

Check it out on Code Sandbox if u want to run it in the browser.

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can do it by creating a simple state like this

function Login() {
const [error,setError]=React.useState("")
  const userRef = React.useRef()
  const passRef = React.useRef()
  const loginErr = React.useRef()
  const handleLogin = async (e) => {
    e.preventDefault()
    const res=requestLogin(userRef.current.value, passRef.current.value, loginErr)
//assuming that above function does a post call via fetch
//and also assuming that in case of wrong credentials error was passed from backend
   const data=res.json()
   if(!res.ok) setError(data.error);
     
  }

  return (
    <form className='login-form' onSubmit={handleLogin}>
        <Field ref={userRef} label='Username:' type='text' />
        <Field ref={passRef} label='Password:' type='password' />
        <div className='button-wrapper'>
          <button type='submit' className='btn'>Login</button>
        </div>
        <div id='error-modal'>{error.length>0 && error}</div>
    </form>
  )
}

export default Login
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda